package com.hlkj.cartservice.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hlkj.cartservice.mapper.TbBrandMapper;
import com.hlkj.cartservice.service.TbBrandService;
import com.hlkj.pojo.common.TbBrand;
import com.hlkj.pojo.common.TbBrandExample;
import com.hlkj.pojo.entity.PageResult;
import com.hlkj.pojo.entity.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TbBrandServiceImpl implements TbBrandService {
    @Resource
    private TbBrandMapper tbBrandMapper;

    @Override
    public List<TbBrand> findAllBrands() {
        return tbBrandMapper.selectByExample(null);
    }

    @Override
    public TbBrand findBrandById(Long id) {
        return tbBrandMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer addBrand(TbBrand brand) {
        return tbBrandMapper.insert(brand);
    }

    @Override
    public Integer updateBrand(TbBrand brand) {
        return tbBrandMapper.updateByPrimaryKeySelective(brand);
    }

    /**
     * 通过id列表删除
     *
     * @param ids id列表
     */
    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            tbBrandMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 使用分页查询
     *
     * @param pageNum  分页数
     * @param pageSize 分页大小
     * @return 分页列表
     */
    @Override
    public PageResult findPage(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);//分页信息
        //通过分页信息返回分页
        Page<TbBrand> page = (Page<TbBrand>) tbBrandMapper.selectByExample(null);
        return new PageResult(page.getTotal(), page.getResult());

    }

    /**
     * 使用查询的分页
     *
     * @param brand    查询信息
     * @param pageNum  分页数
     * @param pageSize 分页大小
     * @return 分页结果
     */
    @Override
    public PageResult findPage(TbBrand brand, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        TbBrandExample tbBrandExample = new TbBrandExample();
        TbBrandExample.Criteria criteria = tbBrandExample.createCriteria();
        if (brand != null) {
            if (brand.getName() != null && brand.getName().length() > 0) {
                criteria.andNameLike("%" + brand.getName() + "%");
            }
            if (brand.getFirstChar() != null && brand.getFirstChar().length() > 0) {
                criteria.andFirstCharEqualTo(brand.getFirstChar());
            }
        }
        Page<TbBrand> page = (Page<TbBrand>) tbBrandMapper.selectByExample(tbBrandExample);
        return new PageResult(page.getTotal(), page.getResult());
    }
}
